import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/sillytavern_service.dart';
export '../services/sillytavern_service.dart' show CharacterCreatingException;
import '../model/notes_character_vo.dart';
import '../model/user.dart';
import '../model/response.dart';
import '../utils/store_util.dart';
import '../static/custom_code.dart';
import '../apis/app.dart';

/// SillyTavern聊天控制器
class SillyTavernChatController extends GetxController {
  final SillyTavernService _service = SillyTavernService();

  // 状态变量
  final characters = <STCharacter>[].obs;
  final chatSessions = <dynamic>[].obs;  // ========== 修改：支持对象列表 ==========
  final messages = <STMessage>[].obs;

  final selectedCharacter = Rx<STCharacter?>(null);
  final selectedSession = Rx<String?>(null);
  final currentUserName = 'User'.obs;
  final currentUserId = ''.obs;  // ========== 新增：当前用户 ID ==========

  final isLoading = false.obs;
  final isSending = false.obs;
  final isInitialized = false.obs;

  // ========== 批量保存优化 ==========
  int _lastSavedMessageCount = 0;  // 上次保存时的消息数量
  int _unsavedMessageCount = 0;     // 未保存的消息数量
  static const int _saveThreshold = 10; // 每累计10条消息保存一次
  Timer? _autoSaveTimer;            // 定时保存计时器
  // ================================

  // ========== 使用次数限制 ==========
  static const String _aiUsageCountKey = 'ai_chat_usage_count';
  static const String _aiUsageDateKey = 'ai_chat_usage_date';
  static const int _freeUsageLimit = 3; // 每天免费3次
  
  // ========== 会员信息缓存 ==========
  static const String _memberInfoCacheKey = 'member_info_cache_time';
  static const Duration _memberInfoCacheDuration = Duration(hours: 24);
  // ================================

  // 故事相关参数（从文章详情页传递）
  String? storyId;
  String? storyTitle;
  String? storyContent;

  @override
  void onInit() {
    super.onInit();
    
    // 获取传递的故事参数
    final args = Get.arguments;
    if (args != null && args is Map) {
      storyId = args['storyId'];
      storyTitle = args['storyTitle'];
      storyContent = args['storyContent'];
      print('接收到故事参数 - ID: $storyId, 标题: $storyTitle');
    }
    
    _initialize();
  }

  @override
  void onClose() {
    // ========== 页面关闭时保存未保存的消息 ==========
    _autoSaveTimer?.cancel();
    
    if (_unsavedMessageCount > 0) {
      print('📤 页面关闭，保存 $_unsavedMessageCount 条未保存的消息...');
      _saveMessages();
    }
    // ============================================
    
    // Request类是单例，不需要dispose
    super.onClose();
  }

  /// 初始化
  Future<void> _initialize() async {
    try {
      isLoading.value = true;

      // ========== 新增：获取当前用户信息 ==========
      await _loadUserInfo();
      // =========================================

      // 获取CSRF Token
      await _service.fetchCsrfToken();

      // 加载角色列表
      await loadCharacters();

      isInitialized.value = true;
    } catch (e) {
      Get.snackbar(
        '初始化失败',
        '无法连接到SillyTavern服务: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('Initialization error: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 加载用户信息
  Future<void> _loadUserInfo() async {
    try {
      final userInfoJson = await readData('userInfo');
      if (userInfoJson != null) {
        final userInfo = jsonDecode(userInfoJson);
        currentUserId.value = userInfo['id']?.toString() ?? '';
        currentUserName.value = userInfo['nickname'] ?? 'User';
        print('👤 当前用户: ${currentUserName.value} (ID: ${currentUserId.value})');
      }
    } catch (e) {
      print('⚠️ 无法加载用户信息: $e');
      // 使用默认值
      currentUserId.value = 'default_user';
      currentUserName.value = 'User';
    }
  }

  /// 从会话对象中提取文件名（公开方法供 UI 使用）
  String extractFileName(dynamic chat) {
    if (chat is String) {
      return chat;
    } else if (chat is Map) {
      return chat['file_name']?.toString() ?? '';
    }
    return '';
  }

  /// 加载角色列表（从后端获取笔记的角色）
  Future<void> loadCharacters() async {
    try {
      if (storyId == null || storyId!.isEmpty) {
        print('⚠️ 没有故事ID，无法加载角色');
        Get.snackbar(
          '提示',
          '缺少故事信息',
          snackPosition: SnackPosition.BOTTOM,
        );
        return;
      }

      print('🔍 开始加载故事 $storyId 的角色...');
      
      // 调用后端接口获取笔记角色（后端会自动提取和创建）
      final notesCharacters = await _service.getNotesCharacters(storyId!);
      
      // 转换为 STCharacter 对象
      characters.value = notesCharacters
          .map((nc) => nc.toSTCharacter())
          .toList();
      
      print('✅ 加载了 ${characters.length} 个角色');
      
      // 显示角色信息
      if (characters.isNotEmpty) {
        final characterNames = characters.map((c) => c.name).join('、');
        Get.snackbar(
          '角色加载成功',
          '共 ${characters.length} 个角色: $characterNames',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 3),
        );
      }
    } on CharacterCreatingException catch (e) {
      // ========== 角色创建中的特殊提示 ==========
      print('⏳ ${e.message}');
      Get.dialog(
        AlertDialog(
          title: Row(
            children: [
              Icon(Icons.psychology, color: Colors.blue, size: 28),
              SizedBox(width: 12),
              Text('AI角色创建中', style: TextStyle(fontSize: 18)),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '系统正在从故事内容中提取角色信息并创建AI对话角色...',
                style: TextStyle(fontSize: 15),
              ),
              SizedBox(height: 16),
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.blue.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.blue.shade200),
                ),
                child: Row(
                  children: [
                    Icon(Icons.access_time, color: Colors.blue.shade700, size: 20),
                    SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        '预计需要 1 分钟\n请稍后重新进入页面',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.blue.shade900,
                          height: 1.5,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              child: Text('我知道了'),
              onPressed: () {
                Get.back();
                Get.back(); // 关闭聊天页面，返回上一页
              },
            ),
          ],
        ),
        barrierDismissible: false,
      );
      // ==========================================
    } catch (e) {
      Get.snackbar(
        '加载失败',
        '无法加载角色列表: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('❌ 加载角色失败: $e');
    }
  }

  /// 选择角色
  Future<void> selectCharacter(STCharacter character) async {
    try {
      isLoading.value = true;
      
      // ========== 切换角色前保存当前会话 ==========
      if (_unsavedMessageCount > 0) {
        print('🔄 切换角色前保存当前会话...');
        await _saveMessages();
      }
      // ======================================
      
      selectedCharacter.value = character;

      // ========== 重置保存状态 ==========
      _lastSavedMessageCount = 0;
      _unsavedMessageCount = 0;
      // ==============================

      print('🎯 选择角色: ${character.name}');

      // ========== 新增：自动查找或创建用户会话 ==========
      if (currentUserId.value.isNotEmpty) {
        // 查找或创建该用户与该角色的会话
        final userChatName = await _service.findOrCreateUserChat(
          character.avatar,
          character.name,
          currentUserId.value,
          currentUserName.value,
        );

        // 重新加载会话列表（包含新创建的会话）
        // chatSessions.value = await _service.getCharacterChats(character.avatar);
        // print('📋 角色共有 ${chatSessions.length} 个会话');

        // 自动选择用户会话
        selectedSession.value = userChatName;
        print('✅ 自动选择用户会话: $userChatName');

        // 加载会话历史
        await loadChatHistory();
        
        Get.snackbar(
          '成功',
          '已进入与 ${character.name} 的聊天',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
      } else {
        // 如果没有用户 ID，只加载会话列表
        // chatSessions.value = await _service.getCharacterChats(character.avatar);
        // print('📋 角色共有 ${chatSessions.length} 个会话');
        
        messages.clear();
        selectedSession.value = null;
        
        // Get.snackbar(
        //   '提示',
        //   '无法获取用户信息，请手动选择会话',
        //   snackPosition: SnackPosition.BOTTOM,
        // );
      }
      // =================================================
    } catch (e) {
      Get.snackbar(
        '加载失败',
        '无法加载会话: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('❌ Error selecting character: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 创建新会话
  Future<void> createNewSession() async {
    if (selectedCharacter.value == null) {
      Get.snackbar('提示', '请先选择角色');
      return;
    }

    try {
      isLoading.value = true;

      // 创建新会话
      final chatName = await _service.createNewChat(
        selectedCharacter.value!.avatar,
        selectedCharacter.value!.name,
        currentUserName.value,
      );

      // ========== 修改：添加会话对象到列表 ==========
      // 重新加载会话列表以包含新创建的会话
      // chatSessions.value = await _service.getCharacterChats(selectedCharacter.value!.avatar);
      selectedSession.value = chatName;
      // ============================================

      // 加载会话历史（新会话只有元数据）
      await loadChatHistory();

      Get.snackbar(
        '成功',
        '新会话已创建',
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      Get.snackbar(
        '创建失败',
        '无法创建新会话: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('Error creating new session: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 选择现有会话
  Future<void> selectSession(String sessionName) async {
    if (selectedCharacter.value == null) {
      Get.snackbar('提示', '请先选择角色');
      return;
    }

    try {
      isLoading.value = true;
      selectedSession.value = sessionName;

      // 加载会话历史
      await loadChatHistory();
    } catch (e) {
      Get.snackbar(
        '加载失败',
        '无法加载会话: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('Error loading session: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 加载聊天历史
  Future<void> loadChatHistory() async {
    if (selectedCharacter.value == null || selectedSession.value == null) {
      return;
    }

    try {
      messages.value = await _service.loadChatHistory(
        selectedCharacter.value!.avatar,
        selectedSession.value!,
      );
      
      // ========== 同步保存状态 ==========
      _lastSavedMessageCount = messages.length;
      _unsavedMessageCount = 0;
      // ===============================
      
      print('Loaded ${messages.length} messages');
    } catch (e) {
      print('Error loading chat history: $e');
    }
  }

  /// 发送消息
  Future<void> sendMessage(String text) async {
    if (selectedCharacter.value == null) {
      Get.snackbar('提示', '请先选择角色');
      return;
    }

    if (selectedSession.value == null) {
      Get.snackbar('提示', '请先选择或创建会话');
      return;
    }

    if (text.trim().isEmpty) {
      return;
    }

    // ========== 检查使用次数并显示提示 ==========
    await _checkAndShowUsageLimitDialog();
    // ========================================

    try {
      isSending.value = true;

      // 添加用户消息
      final userMessage = STMessage.user(
        name: currentUserName.value,
        content: text.trim(),
      );
      messages.add(userMessage);

      // ========== 优化：不立即保存 ==========
      _unsavedMessageCount++;
      print('📝 新增用户消息，未保存: $_unsavedMessageCount 条');
      // ==================================

      // 生成AI回复
      final systemPrompt = _buildSystemPrompt();
      final aiReply = await _service.generateReply(
        chatHistory: messages.toList(),
        systemPrompt: systemPrompt,
      );

      // 添加AI消息
      final aiMessage = STMessage.assistant(
        name: selectedCharacter.value!.name,
        content: aiReply,
      );
      messages.add(aiMessage);

      // ========== 优化：累计消息，到达阈值才保存 ==========
      _unsavedMessageCount++;
      print('📝 新增AI消息，未保存: $_unsavedMessageCount 条');
      
      // 如果未保存消息达到阈值（10条），立即保存
      if (_unsavedMessageCount >= _saveThreshold) {
        print('💾 达到保存阈值($_saveThreshold条)，开始保存...');
        await _saveMessages();
      }
      // ===========================================
      
      // ========== 增加使用次数 ==========
      await _incrementUsageCount();
      // ===============================
      
    } catch (e) {
      Get.snackbar(
        '发送失败',
        '无法发送消息: $e',
        snackPosition: SnackPosition.BOTTOM,
      );
      print('Error sending message: $e');
    } finally {
      isSending.value = false;
    }
  }

  /// ========== 检查使用次数限制 ==========
  Future<void> _checkAndShowUsageLimitDialog() async {
    try {
      // ========== 检查会员状态（带缓存机制）==========
      final userInfoJson = await readData('userInfo');
      if (userInfoJson == null) {
        print('⚠️ 无用户信息，检查免费次数...');
      } else {
        final userInfo = User.fromJson(jsonDecode(userInfoJson));
        
        // 检查会员信息缓存时间
        final prefs = await SharedPreferences.getInstance();
        final lastCacheTime = prefs.getString(_memberInfoCacheKey);
        final shouldRefresh = _shouldRefreshMemberInfo(lastCacheTime);
        
        if (shouldRefresh) {
          // 超过24小时，重新获取会员信息
          print('🔄 会员信息缓存过期，重新获取...');
          await _refreshMemberInfoSilently(userInfo);
          
          // 重新读取更新后的用户信息
          final updatedUserInfoJson = await readData('userInfo');
          if (updatedUserInfoJson != null) {
            final updatedUserInfo = User.fromJson(jsonDecode(updatedUserInfoJson));
            if (updatedUserInfo.hasAiChatMember) {
              print('✅ 用户是AI聊天会员，无使用限制');
              print('   开通时间: ${updatedUserInfo.aiChatMemberOpenTime}');
              return;
            }
          }
        } else {
          // 缓存有效，直接使用本地数据
          print('📦 使用缓存的会员信息');
          if (userInfo.hasAiChatMember) {
            print('✅ 用户是AI聊天会员，无使用限制');
            print('   开通时间: ${userInfo.aiChatMemberOpenTime}');
            return;
          }
        }
        
        print('⚠️ 用户不是会员，检查免费次数...');
      }
      // ================================
      
      final prefs = await SharedPreferences.getInstance();
      
      // 获取今天的日期
      final today = DateTime.now().toString().split(' ')[0]; // yyyy-MM-dd
      
      // 获取上次使用日期和次数
      final lastUsageDate = prefs.getString(_aiUsageDateKey);
      int usageCount = prefs.getInt(_aiUsageCountKey) ?? 0;
      
      // 如果日期不同，重置次数
      if (lastUsageDate != today) {
        usageCount = 0;
        await prefs.setString(_aiUsageDateKey, today);
        await prefs.setInt(_aiUsageCountKey, 0);
      }
      
      // 如果超过免费次数，显示付费提示
      if (usageCount >= _freeUsageLimit) {
        print('⚠️ AI使用次数已超过限制: $usageCount/$_freeUsageLimit');
        
        // 显示付费提示对话框
        Get.dialog(
          AlertDialog(
            title: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.orange),
                SizedBox(width: 8),
                Text('使用提示'),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'AI使用费用高昂',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 12),
                Text(
                  '您今天已使用 $usageCount 次AI对话\n\n为了提供更好的服务，请考虑升级：',
                  style: TextStyle(fontSize: 14),
                ),
                SizedBox(height: 12),
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.blue.shade50,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.blue.shade200),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.card_membership, 
                            color: Colors.blue, size: 20),
                          SizedBox(width: 8),
                          Text(
                            '月会员 - ¥10',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.blue.shade700,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 8),
                      Text(
                        '• 无限次AI对话\n• 更快响应速度\n• 专属客服支持',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey.shade700,
                        ),
                      ),
                      SizedBox(height: 12),
                      Row(
                        children: [
                          Icon(Icons.wechat, 
                            color: Colors.green, size: 20),
                          SizedBox(width: 8),
                          Text(
                            '微信: zxsr20',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                              color: Colors.green.shade700,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                child: Text('我知道了'),
                onPressed: () => Get.back(),
              ),
              TextButton(
                child: Text(
                  '已付费，刷新状态',
                  style: TextStyle(color: Colors.green),
                ),
                onPressed: () async {
                  Get.back();
                  await _refreshMemberStatus();
                },
              ),
            ],
          ),
          barrierDismissible: true,
        );
      }
    } catch (e) {
      print('❌ 检查使用次数失败: $e');
    }
  }

  /// 增加使用次数
  Future<void> _incrementUsageCount() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final today = DateTime.now().toString().split(' ')[0];
      final lastUsageDate = prefs.getString(_aiUsageDateKey);
      int usageCount = prefs.getInt(_aiUsageCountKey) ?? 0;
      
      // 如果是新的一天，重置次数
      if (lastUsageDate != today) {
        usageCount = 0;
        await prefs.setString(_aiUsageDateKey, today);
      }
      
      // 增加次数
      usageCount++;
      await prefs.setInt(_aiUsageCountKey, usageCount);
      
      print('📊 AI使用次数: $usageCount/$_freeUsageLimit');
    } catch (e) {
      print('❌ 更新使用次数失败: $e');
    }
  }

  /// 检查是否需要刷新会员信息
  bool _shouldRefreshMemberInfo(String? lastCacheTime) {
    if (lastCacheTime == null) {
      print('📭 无会员信息缓存');
      return true;
    }
    
    try {
      final cacheTime = DateTime.parse(lastCacheTime);
      final now = DateTime.now();
      final difference = now.difference(cacheTime);
      
      if (difference > _memberInfoCacheDuration) {
        print('⏰ 会员信息缓存已过期（${difference.inHours}小时）');
        return true;
      } else {
        print('✅ 会员信息缓存有效（剩余${_memberInfoCacheDuration.inHours - difference.inHours}小时）');
        return false;
      }
    } catch (e) {
      print('❌ 解析缓存时间失败: $e');
      return true;
    }
  }

  /// 静默刷新会员信息（后台更新，不显示提示）
  Future<void> _refreshMemberInfoSilently(User currentUser) async {
    try {
      print('🔄 静默刷新会员信息...');
      
      // 调用会员信息API
      HttpResponse response = await UserApi.getMemberInfo(currentUser.id);
      
      if (response.code == StatusCode.getSuccess) {
        // 更新本地用户信息中的会员字段
        final memberData = response.data;
        currentUser.isAiChatMember = memberData['isAiChatMember'] ?? 0;
        currentUser.aiChatMemberOpenTime = memberData['aiChatMemberOpenTime'];
        currentUser.isRealChatMember = memberData['isRealChatMember'] ?? 0;
        currentUser.realChatMemberOpenTime = memberData['realChatMemberOpenTime'];
        
        // 保存更新后的用户信息
        await saveData('userInfo', jsonEncode(currentUser.toJson()));
        
        // 保存缓存时间
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString(_memberInfoCacheKey, DateTime.now().toIso8601String());
        
        print('✅ 会员信息静默刷新成功');
        print('   AI聊天会员: ${currentUser.hasAiChatMember}');
        print('   真人聊天会员: ${currentUser.hasRealChatMember}');
      } else {
        print('❌ 静默刷新失败: ${response.msg}');
      }
    } catch (e) {
      print('❌ 静默刷新异常: $e');
    }
  }

  /// 刷新会员状态（手动触发，显示提示）
  Future<void> _refreshMemberStatus() async {
    try {
      Get.snackbar(
        '刷新中',
        '正在获取最新会员状态...',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 1),
      );
      
      // 获取当前用户ID
      final userInfoJson = await readData('userInfo');
      if (userInfoJson == null) {
        Get.snackbar('错误', '无法获取用户信息', snackPosition: SnackPosition.BOTTOM);
        return;
      }
      
      final currentUser = User.fromJson(jsonDecode(userInfoJson));
      
      // 调用新的会员信息API
      HttpResponse response = await UserApi.getMemberInfo(currentUser.id);
      
      if (response.code == StatusCode.getSuccess) {
        // 更新本地用户信息中的会员字段
        final memberData = response.data;
        currentUser.isAiChatMember = memberData['isAiChatMember'] ?? 0;
        currentUser.aiChatMemberOpenTime = memberData['aiChatMemberOpenTime'];
        currentUser.isRealChatMember = memberData['isRealChatMember'] ?? 0;
        currentUser.realChatMemberOpenTime = memberData['realChatMemberOpenTime'];
        
        // 保存更新后的用户信息
        await saveData('userInfo', jsonEncode(currentUser.toJson()));
        
        // 更新缓存时间
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString(_memberInfoCacheKey, DateTime.now().toIso8601String());
        
        print('✅ 会员信息已更新:');
        print('   AI聊天会员: ${currentUser.hasAiChatMember}');
        print('   真人聊天会员: ${currentUser.hasRealChatMember}');
        
        if (currentUser.hasAiChatMember) {
          Get.snackbar(
            '✅ 刷新成功',
            '欢迎 AI聊天会员！您现在可以无限使用AI聊天功能\n${currentUser.aiChatMemberOpenTimeDesc}',
            snackPosition: SnackPosition.BOTTOM,
            backgroundColor: Colors.green.shade100,
            duration: const Duration(seconds: 3),
          );
        } else {
          Get.snackbar(
            '提示',
            '未检测到AI聊天会员信息，如已付费请等待后台处理（约5分钟）',
            snackPosition: SnackPosition.BOTTOM,
            duration: const Duration(seconds: 3),
          );
        }
      } else {
        Get.snackbar('错误', '刷新失败: ${response.msg}', snackPosition: SnackPosition.BOTTOM);
      }
    } catch (e) {
      print('❌ 刷新会员状态失败: $e');
      Get.snackbar('错误', '刷新失败: $e', snackPosition: SnackPosition.BOTTOM);
    }
  }
  // ====================================

  /// ========== 批量保存消息 ==========
  Future<void> _saveMessages() async {
    if (_unsavedMessageCount == 0) {
      print('⏭️ 没有未保存的消息');
      return;
    }

    if (selectedCharacter.value == null || selectedSession.value == null) {
      print('⚠️ 无法保存：角色或会话未选择');
      return;
    }

    try {
      final unsavedMessages = messages.skip(_lastSavedMessageCount).toList();
      
      print('💾 保存 ${unsavedMessages.length} 条未保存的消息...');
      
      final success = await _service.saveNewMessages(
        selectedCharacter.value!.avatar,
        selectedSession.value!,
        unsavedMessages,
      );
      
      if (success) {
        _lastSavedMessageCount = messages.length;
        _unsavedMessageCount = 0;
        print('✅ 保存成功！当前总消息数: ${messages.length}');
      } else {
        print('❌ 保存失败');
      }
    } catch (e) {
      print('❌ 保存消息异常: $e');
    }
  }
  // ================================

  /// 构建系统提示词
  String _buildSystemPrompt() {
    final character = selectedCharacter.value!;
    final parts = <String>[];

    parts.add('你是${character.name}。');

    if (character.personality != null && character.personality!.isNotEmpty) {
      parts.add('性格：${character.personality}');
    }

    if (character.scenario != null && character.scenario!.isNotEmpty) {
      parts.add('场景：${character.scenario}');
    }

    if (character.description != null && character.description!.isNotEmpty) {
      parts.add('描述：${character.description}');
    }

    // 添加故事背景信息
    if (storyTitle != null && storyTitle!.isNotEmpty) {
      parts.add('\n【故事背景】');
      parts.add('故事标题：$storyTitle');
    }

    if (storyContent != null && storyContent!.isNotEmpty) {
      // 截取前500个字符
      final truncatedContent = storyContent!.length > 100 
          ? storyContent!.substring(0, 100) + '...'
          : storyContent;
      parts.add('故事内容：$truncatedContent');
      parts.add('\n请基于这个故事的背景和你的角色设定，与用户进行对话。');
    }

    return parts.join('\n');
  }

  /// 获取实际显示的消息列表（过滤元数据）
  List<STMessage> get displayMessages {
    return messages.where((m) => !m.isMetadata).toList();
  }
  
  /// 跳转到AI创作页面生成故事续写
  Future<void> navigateToStoryGeneration() async {
    if (displayMessages.isEmpty) {
      Get.snackbar(
        '提示',
        '暂无对话内容',
        snackPosition: SnackPosition.BOTTOM,
      );
      return;
    }
    
    // 构建对话内容摘要
    StringBuffer dialogueContent = StringBuffer();
    
    // 获取最近的10条消息（或全部消息如果少于10条）
    final recentMessages = displayMessages.length > 10
        ? displayMessages.sublist(displayMessages.length - 10)
        : displayMessages;
    
    dialogueContent.writeln('【与${selectedCharacter.value?.name ?? "角色"}的对话】\n');
    
    for (var message in recentMessages) {
      dialogueContent.writeln('${message.name}：${message.mes}\n');
    }
    
    // 构建辅助提示词
    String assistantPrompt = '请根据上述对话内容，续写故事情节。';
    if (storyTitle != null && storyTitle!.isNotEmpty) {
      assistantPrompt = '基于故事《$storyTitle》和以上对话，请续写故事情节。保持与原故事和对话的连贯性。';
    }
    
    print('🎬 跳转到AI创作页面');
    print('   对话内容长度: ${dialogueContent.length}');
    print('   辅助提示词: $assistantPrompt');
    
    // 跳转到AI创作页面，并传递对话内容
    final result = await Get.toNamed(
      '/ai/creation',
      arguments: {
        'isContinuation': storyId != null && storyId!.isNotEmpty,
        'parentNotesId': storyId != null ? int.tryParse(storyId!) ?? 0 : 0,
        'creationType': 1, // 1表示AI对话续写
        'dialogueContent': dialogueContent.toString(),
        'assistantPrompt': assistantPrompt,
      },
    );
    
    // 如果用户采用了生成的内容，返回到发布页面
    if (result != null && result is Map && result['adopted'] == true) {
      print('✅ 用户采用了生成的内容');
      print('   内容长度: ${result['content']?.toString().length ?? 0}');
      
      // 关闭聊天页面，并将结果传递给发布页面
      Get.back(result: result);
      
      // 显示提示
      Get.snackbar(
        '✅ 内容已生成',
        '已将生成的内容填充到创作页面',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    }
  }
}

